package com.hzxy.yiyid.web.tool.baidu;

import com.baidu.aip.nlp.AipNlp;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @ClassName BaiduAI
 * @Description TOOD
 * @Author RAICOM2023
 * @Date 2023/4/28 13:44
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "baidu")
@PropertySource("classpath:baidu.properties")
public class BaiduAI {

    private static String appId;

    private static String apiKey;

    private static String secretKey;

    @Value("${bd.app.id}")
    public void setAppId(String str) {
        appId = str;
    }
    @Value("${bd.api.key}")
    public void setApiKey(String str) {
        apiKey = str;
    }
    @Value("${bd.secret.key}")
    public void setSecretKey(String str) {
        secretKey = str;
    }

    private static boolean NLP_INIT_FLAG = false;
    private static boolean OCR_INIT_FLAG = false;

    private static final int SOCKET_TIMEOUT_IN_MILLIS = 60000;
    private static final int CONNECTION_TIMEOUT_IN_MILLIS = 2000;

    private static AipNlp NLP_CLIENT = null;

    // 文字识别
    private static AipOcr OCR_CLIENT = null;

    public static void initNlpClient(){
        if(!NLP_INIT_FLAG){
            NLP_CLIENT = new AipNlp(appId, apiKey, secretKey);
            NLP_CLIENT.setConnectionTimeoutInMillis(CONNECTION_TIMEOUT_IN_MILLIS);
            NLP_CLIENT.setSocketTimeoutInMillis(SOCKET_TIMEOUT_IN_MILLIS);
            NLP_INIT_FLAG = true;
        }
    }

    public static void initOcrClient(){
        if(!OCR_INIT_FLAG){
            OCR_CLIENT = new AipOcr(appId, apiKey, secretKey);
            OCR_CLIENT.setConnectionTimeoutInMillis(CONNECTION_TIMEOUT_IN_MILLIS);
            OCR_CLIENT.setSocketTimeoutInMillis(SOCKET_TIMEOUT_IN_MILLIS);
            OCR_INIT_FLAG = true;
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //地址识别
     * @Date 15:14 2023/3/6
     * @Param [text]
     * @return org.json.JSONObject
     **/
    public static JSONObject NLP_ADDRESS(String text) throws Exception{
        initNlpClient();
        JSONObject res = NLP_CLIENT.address(text,null);
        return res;
    }

    /*
     * @Author RAICOM2023
     * @Description //手写文字识别
     * @Date 17:54 2023/5/3
     * @Param [bytes]
     * @return org.json.JSONObject
     **/
    public static JSONObject BASIC(byte[] bytes){
        initOcrClient();
        JSONObject res = OCR_CLIENT.basicAccurateGeneral(bytes,null);
        return res;
    }

}
